const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');

// 获取字体样式列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      type_id, 
      search,
      populate 
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];
    
    if (type_id) {
      whereClause += ' AND fs.type_id = ?';
      params.push(type_id);
    }
    
    if (search) {
      whereClause += ' AND fs.name LIKE ?';
      params.push(`%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.execute(
      `SELECT COUNT(*) as total FROM font_styles fs ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        fs.id,
        fs.name,
        fs.type_id,
        fs.preview,
        fs.font_family,
        fs.font_size,
        fs.font_weight,
        fs.color,
        fs.style_data,
        fs.created_at,
        fs.updated_at,
        ${populate === '*' ? 'fst.name as type_name' : 'NULL as type_name'}
      FROM font_styles fs
      ${populate === '*' ? 'LEFT JOIN font_style_types fst ON fs.type_id = fst.id' : ''}
      ${whereClause}
      ORDER BY fs.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.execute(query, [...params, limit, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        preview: row.preview,
        font_family: row.font_family,
        font_size: row.font_size,
        font_weight: row.font_weight,
        color: row.color,
        style_data: row.style_data ? JSON.parse(row.style_data) : null,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          font_style_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        })
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          pageCount: Math.ceil(total / parseInt(pageSize)),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取字体样式列表失败:', error);
    res.status(500).json({ error: '获取字体样式列表失败' });
  }
});

// 获取单个字体样式详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { populate } = req.query;
    
    const query = `
      SELECT 
        fs.*,
        ${populate === '*' ? 'fst.name as type_name' : 'NULL as type_name'}
      FROM font_styles fs
      ${populate === '*' ? 'LEFT JOIN font_style_types fst ON fs.type_id = fst.id' : ''}
      WHERE fs.id = ?
    `;
    
    const [rows] = await db.execute(query, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '字体样式不存在' });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        name: row.name,
        preview: row.preview,
        font_family: row.font_family,
        font_size: row.font_size,
        font_weight: row.font_weight,
        color: row.color,
        style_data: row.style_data ? JSON.parse(row.style_data) : null,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          font_style_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        })
      }
    };
    
    res.json({ data });
  } catch (error) {
    console.error('获取字体样式详情失败:', error);
    res.status(500).json({ error: '获取字体样式详情失败' });
  }
});

module.exports = router;